
import blobToFile from "./blobToFile"
import toCanvas from "html2canvas"
import {Time} from "cdd-lib"
import {anyObj} from 'cdd-lib/src/js/lib/lib'
class ToImage {

  /**
   * 获取图片或者上传blob
   * @param {object} params 参数
   * @param {HTMLElement} params.target 需要生成图片的dom
   * @param {boolean} params.isBlob 是否返回blob
   * @param {string} params.type 图片类型
   * @return Promise<string|Blob> 返回promise
   */
  static generate (params: {target: HTMLElement, isBlob?: boolean, type?: string, justPage?: boolean}, options?: anyObj): Promise<string | Blob> {
    // 初始数据
    params = Object.assign({}, {isBlob: false, type: 'image/png', justPage: false}, params)
    options = options || {}
    if (params.justPage) {
      options.height = screen.height
    }

    return new Promise((reso, rej) => {
      toCanvas(params.target, options).then((canvas: HTMLCanvasElement) => {

        if (params.isBlob) {
          return canvas.toBlob((blob) => {
            if (blob) {
              reso(<Blob>blob)
            } else {
              rej(blob)
            }
          },
            params.type
          )
        } else {
          reso(canvas.toDataURL())
        }
      })
    })
  }

  // 获取文件
  static async getImageFile (params: {target: HTMLElement, name?: string, quality?: number, type?: string, justPage?: boolean}, options?: anyObj) {
    params = Object.assign({}, {isBlob: true, quality: .8, type: 'image/png'}, params)
    let name = params.name
    // 如果没有名字则进行自定义名字
    if (!params.name) {
      const time = new Time({dateSeparator: '', timeSeparator: ''})
      name = time.dateStr + time.timeStr + '.' + params.type?.split('/')[ 1 ]
    }
    const blob = await ToImage.generate(params, options)
    return await blobToFile(<Blob>blob, <string>name)
  }
}

const capture = ToImage.generate
const getImageFile = ToImage.getImageFile
export {capture, getImageFile}
export default {
  capture,
  getImageFile
}
